package com.xinruke.hostels.reservation.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinruke.hostels.cache.extract.extractor.DictInfoCacheExtractor;
import com.xinruke.hostels.cache.extract.extractor.HotelInfoCacheExtractor;
import com.xinruke.hostels.central.manage.interfaces.dto.HotelInfoDetailQueryResultDTO;
import com.xinruke.hostels.common.cache.ReservationUserCache;
import com.xinruke.hostels.common.cache.util.SysCodeUtil;
import com.xinruke.hostels.common.cache.util.SysSqlParamUtil;
import com.xinruke.hostels.common.cache.vo.LoginReservationResultVO;
import com.xinruke.hostels.common.constants.BusiConstant;
import com.xinruke.hostels.common.constants.SysDicConstant;
import com.xinruke.hostels.common.po.YwYudingCantingDingdan;
import com.xinruke.hostels.common.po.YwYudingCantingDingdanZixiang;
import com.xinruke.hostels.common.po.constants.YwYudingCantingDingdanConstants;
import com.xinruke.hostels.common.util.DateTool;
import com.xinruke.hostels.common.vo.MhDingdanCantingVO;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.common.vo.query.RowsDataVO;
import com.xinruke.hostels.reservation.interfaces.dto.*;
import com.xinruke.hostels.reservation.mapper.YwYudingCantingDingdanMapper;
import com.xinruke.hostels.reservation.mapper.YwYudingCantingDingdanZixiangMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RestaurantOrderService {

    @Autowired
    private DictInfoCacheExtractor dictInfoCacheExtractor;

    @Autowired
    private YwYudingCantingDingdanMapper ywYudingCantingDingdanMapper;

    @Autowired
    private YwYudingCantingDingdanZixiangMapper ywYudingCantingDingdanZixiangMapper;

    @Resource
    private ReservationUserCache reservationUserCache;

    @Resource
    private HotelInfoCacheExtractor hotelInfoCacheExtractor;


//    public ResultVO<String> submit(RestaurantSubmitInfoDto params) {
//        ResultVO<String> resultVO = ResultVO.success();
//        checkIsCanReservation(params, resultVO);
//        if (resultVO.getCode() == ResultVO.FAIL) {
//            return resultVO;
//        }
//        MhDingdanCantingVO dingdanCanting = new MhDingdanCantingVO();
//        BeanUtils.copyProperties(params, dingdanCanting);
//        String dingdanhao = String.valueOf(System.currentTimeMillis()).substring(5);
//        // TODO: 2019/6/27 订单号生成
//        dingdanCanting.setDingdanhao(dingdanhao);
//
//        dingdanCanting.setShanchubiaoshi(SysDicConstant.DELFLAG_0);
//        dingdanCanting.setZhuangtai(MhDingdanCantingVO.ZHUANGTAI_DAISHENHE);
//        LoginReservationResultVO reservationUserInfo = reservationUserCache.getLoginReservationUserInfo();
//        dingdanCanting.setHuiyuanId(reservationUserInfo.getId());//当前用户id
//        dingdanCanting.setChuangjianshijian(new Date());
//        dingdanCanting.setGengxinshijian(new Date());
//
//        int count = mhDingdanCantingMapper.insertSelective(dingdanCanting);
//        if (count == 0) {
//            resultVO = ResultVO.fail();
//        }
//        return resultVO;
//    }


    public ResultVO<String> submit(RestaurantSubmitInfoDto params) {
        ResultVO<String> resultVO = ResultVO.success();
        checkIsCanReservation(params, resultVO);
        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }
        YwYudingCantingDingdan dingdanCanting = new YwYudingCantingDingdan();
        BeanUtils.copyProperties(params, dingdanCanting);
        String dingdanhao = String.valueOf(System.currentTimeMillis()).substring(5);
        // TODO: 2019/6/27 订单号生成
        dingdanCanting.setDingdanhao(dingdanhao);
        dingdanCanting.setLaiyuan(YwYudingCantingDingdanConstants.LAIYUAN_WANGZHAN);
//        dingdanCanting.setZhengjianhao();
//        dingdanCanting.setZhengjianleixing();
        dingdanCanting.setZhuangtai(YwYudingCantingDingdanConstants.ZHUANGTAI_YITIJIAO);
        LoginReservationResultVO reservationUserInfo = reservationUserCache.getLoginReservationUserInfo();
        dingdanCanting.setHuiyuanId(reservationUserInfo.getId());//当前用户id
        Date nowDate = DateTool.getNow();
        dingdanCanting.setChuangjianshijian(nowDate);
        dingdanCanting.setGengxinshijian(nowDate);
        dingdanCanting.setShanchubiaoshi(SysDicConstant.DELFLAG_0);

        int count = ywYudingCantingDingdanMapper.insertSelective(dingdanCanting);
        if (count == 0) {
            resultVO = ResultVO.fail();
        }
        //用餐日期
        String yongcanDate = DateTool.getDateTime(DateTool.DEFAULT_DATE_FORMAT, params.getYongcanshijian());
        String[] yongcanxuanxiangArray = params.getYongcanxuanxiang().split(",");
        log.info("yongcanxuanxiang={} yongcanxuanxiangArray={}", params.getYongcanxuanxiang(), JSONObject.toJSONString(yongcanxuanxiangArray));
        for (String yongcanleibie : yongcanxuanxiangArray) {
            YwYudingCantingDingdanZixiang ywYudingCantingDingdanZixiang = new YwYudingCantingDingdanZixiang();
            ywYudingCantingDingdanZixiang.setJiucanleibie(Byte.parseByte(yongcanleibie));
            ywYudingCantingDingdanZixiang.setJiudianId(params.getJiudianId());
            ywYudingCantingDingdanZixiang.setCanzhuoId(params.getCantingId());
            ywYudingCantingDingdanZixiang.setYongcanrenshu(params.getYongcanrenshu());
            ywYudingCantingDingdanZixiang.setCanzhuomingcheng(params.getYongcanmingcheng());
            ywYudingCantingDingdanZixiang.setDingdanhao(dingdanhao);
            ywYudingCantingDingdanZixiang.setDingdanId(dingdanCanting.getId());
            String yongcanTime = BusiConstant.YONGCAN_LEIBIE.get(yongcanleibie);
            if (yongcanTime == null) {
                log.error("获取用餐类别结束时间error");
                continue;
            }
            String yongcanDateTime = yongcanDate + " " + yongcanTime;
            log.info("yongcanTime={} yongcanDateTime={}", yongcanTime, yongcanDateTime);
            Date yongcanKaishiDateTime = DateTool.parse(yongcanDateTime, "yyyy-MM-dd HH:mm");
            log.info("yongcanKaishiDateTime={}", yongcanKaishiDateTime);

            //用餐结束时间，默认开始时间3小时之后
            Date yongcanJieshuDateTime = DateTool.addDaysByField(yongcanKaishiDateTime, 3, Calendar.HOUR);
            log.info("yongcanJieshuDateTime={}", yongcanJieshuDateTime);

            ywYudingCantingDingdanZixiang.setKaishishijian(yongcanKaishiDateTime);
            ywYudingCantingDingdanZixiang.setJieshushijian(yongcanJieshuDateTime);
            ywYudingCantingDingdanZixiang.setYudingxingming(params.getYudingrenxingming());
            ywYudingCantingDingdanZixiang.setLianxidianhua(params.getYudingrendianhua());
            ywYudingCantingDingdanZixiang.setChuangjianshijian(nowDate);
            ywYudingCantingDingdanZixiang.setGengxinshijian(nowDate);
            ywYudingCantingDingdanZixiang.setShanchubiaoshi(SysDicConstant.DELFLAG_0);
            ywYudingCantingDingdanZixiangMapper.insertSelective(ywYudingCantingDingdanZixiang);
        }
        return resultVO;
    }

    public ResultVO<String> cancel(RestaurantCancelDto params) {
        ResultVO<String> resultVO = ResultVO.success();
        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }
        YwYudingCantingDingdan dingdanCanting = new YwYudingCantingDingdan();
        dingdanCanting.setId(params.getId());
        dingdanCanting.setZhuangtai(MhDingdanCantingVO.ZHUANGTAI_QUXIAO);
        dingdanCanting.setGengxinshijian(new Date());
        int count = ywYudingCantingDingdanMapper.updateByPrimaryKeySelective(dingdanCanting);
        if (count == 0) {
            resultVO = ResultVO.fail();
        }
        return resultVO;
    }

    public ResultVO<String> del(RestaurantDelDto params) {
        return null;
    }

    public RowsDataVO<RestaurantListQueryResultDto> list(RestaurantListQueryDto params) {
        //获取当前用户
        LoginReservationResultVO userInfo = reservationUserCache.getLoginReservationUserInfo();
        params.setCurrentUserId(userInfo.getId());
        RowsDataVO<RestaurantListQueryResultDto> dataVO = new RowsDataVO<>();

        String order = params.getOrderFields().stream().filter(o -> !StringUtils.isEmpty(o.getOrderField())).map(o -> o.getOrderField() + (o.getOrderDesc() ? " DESC" : " ASC")).reduce((s1, s2) -> s1 + "," + s2).orElse("");
        Page<RestaurantListQueryResultDto> page = PageHelper.startPage(params.getPageNo(), params.getPageSize(), order);
        List<MhDingdanCantingVO> list = ywYudingCantingDingdanMapper.list(params);

        List<RestaurantListQueryResultDto> resultList = list.stream().map(n -> {
            RestaurantListQueryResultDto dto = new RestaurantListQueryResultDto();
            BeanUtils.copyProperties(n, dto);
            //调用接口 填充酒店名称
            //log.info("hotelInfo={}", JSONObject.toJSONString(dto));
            HotelInfoDetailQueryResultDTO hotelInfo = hotelInfoCacheExtractor.getJiudianInfoById(dto.getJiudianId());
            if (hotelInfo != null) {
                dto.setJiudianmingcheng(hotelInfo.getMingcheng() + "(" + hotelInfo.getXiangxidizhi() + ")");
            }
            //dto.setJiudianmingcheng(SysSqlParamUtil.getSysParamDesc(SysDicConstant.JIUDIAN_MINGCHENG.toUpperCase(), dto.getJiudianId()));
            dto.setZhuangtaiMingCheng(SysCodeUtil.getSysParamDesc(SysDicConstant.DINGDANZHUANGTAI.toUpperCase(), dto.getZhuangtai()));
            return dto;
        }).collect(Collectors.toList());

        dataVO.setPageNo(page.getPageNum());
        dataVO.setTotalRecords(page.getTotal());
        dataVO.setTotalPages(page.getPages());
        dataVO.setRows(resultList);
        return dataVO;
    }

    public ResultVO<RestaurantDetailQueryResultDto> detail(RestaurantDetailQueryDto params) {
        MhDingdanCantingVO dingdanCanting = ywYudingCantingDingdanMapper.selectEntityById(params.getId());
        if (dingdanCanting == null) {
            return ResultVO.fail("查询数据失败");
        }
        RestaurantDetailQueryResultDto dto = new RestaurantDetailQueryResultDto();
        BeanUtils.copyProperties(dingdanCanting, dto);
        dto.setYongcanshijian(DateTool.parse(DateTool.getDateTime(DateTool.DEFAULT_DATE_FORMAT, dto.getKaishishijian()), DateTool.DEFAULT_DATE_FORMAT));
        dto.setJiudianmingcheng(SysSqlParamUtil.getSysParamDesc(SysDicConstant.JIUDIAN_MINGCHENG.toUpperCase(), dto.getJiudianId()));
        dto.setZhuangtaiMingCheng(dictInfoCacheExtractor.getDictValue(SysDicConstant.DINGDANZHUANGTAI, dto.getZhuangtai()));
        ResultVO<RestaurantDetailQueryResultDto> resultVO = ResultVO.success();
        resultVO.setData(dto);
        return resultVO;
    }

    private ResultVO checkIsCanReservation(RestaurantSubmitInfoDto params, ResultVO resultVO) {
        /*RestaurantDetailQueryDTO request = new RestaurantDetailQueryDTO();
        request.setId(params.getCantingId());
        ResultVO<RestaurantDetailQueryResultDTO> restaurantDetailResultVO = restaurantAPI.detail(request);

        if (restaurantDetailResultVO.getCode() == ResultVO.FAIL) {
            resultVO.setCode(ResultVO.FAIL);
            resultVO.setMessage("不存在此餐厅");
            return resultVO;
        }
        RestaurantDetailQueryResultDTO detail = restaurantDetailResultVO.getData();
         if (detail.getZuoweishu() <= 0) {
            resultVO.setCode(ResultVO.FAIL);
            resultVO.setMessage("手慢了，餐厅：" + 1001 + "已经没有库存了");
        }
        return resultVO;*/
        return ResultVO.success();
    }
}
